import { CacheService } from '@app/cache';
import { ConfigureService } from '@app/configure';
import { PlatformData } from '@app/db/common/entities/PlatformData';
import { ChargeOrder } from '@app/db/entities/ChargeOrder';
import { User } from '@app/db/entities/User';
import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class PayService {
    public wxAccessTokenKey:string

    public wechatConf:{[key:string] : any};
    public alipayConf:{[key:string] : any};
    public wxAccessToken:string;

    private prvQueryTime = 0
    constructor(
        @InjectRepository(PlatformData, 'common') protected platform:Repository<PlatformData>,
        private config:ConfigureService,
        private http:HttpService,
        private cache:CacheService
    ){
        this.wxAccessTokenKey = this.config.get('wxAccessTokenKey')
    }


    async conf() {
        const time = Date.now()
        if((time - this.prvQueryTime) < 360000) return
        this.prvQueryTime = time
        const data = await this.platform.find({
            select : ['wechat', 'alipay']
        })

        if(data.length > 0) {
            this.wechatConf = data[0].wechat
            this.alipayConf = data[0].alipay
        }

        const wxAccessToken = await this.cache.get(this.wxAccessTokenKey)
        if(wxAccessToken) {
            this.wxAccessToken = wxAccessToken
        }

    }

    //免密支付取消订单
    async payscoreServiceorderCancel(out_order_no:string, reason:string){
        try {
            if(!this.wechatConf) return null
            const res = await this.http.axiosRef.post(`https://api.mch.weixin.qq.com/v3/payscore/serviceorder/${out_order_no}/cancel`, {
                service_id: this.wechatConf.serviceId,
                appid: this.wechatConf.appid,
                reason: reason
            })

            return res.statusText == 'OK' ? res.data : null

        } catch (error) {
            
            console.log(error.message)
        }
        
        return null
    }

    //免密支付完结
    async payscoreServiceorderComplete(out_order_no:string, amount:number){
        amount = amount * 100
        try {
            if(!this.wechatConf) return null
            const res = await this.http.axiosRef.post(`https://api.mch.weixin.qq.com/v3/payscore/serviceorder/${out_order_no}/complete`, {
                service_id: this.wechatConf.serviceId,
                appid: this.wechatConf.appid,
                post_payments: [
                    {name : '充电费用', amount : amount}
                ],
                total_amount : amount
            })

            return res.statusText == 'OK' ? res.data : null

        } catch (error) {
            
            console.log(error.message)
        }
        
        return null
    }

    endNotify(user:User, order) {
        try {
            if(user.source == 1) { //微信
                const f = eval(`(${this.wechatConf.chargeFinishMsgFunc})`);
                if(f) {
                    this.http.axiosRef.post(
                        'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' + this.wxAccessToken,
                        f(user.openid, this.wechatConf.chargeFinishMsgTemplate, order)
                    )
                }
            }
        } catch (error) {
            console.log(error)
        }
    }
}
